package com.stylefeng.guns.wx.modular.auth.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.stylefeng.guns.wx.common.persistence.model.UserNovel;
import com.stylefeng.guns.wx.modular.auth.service.IWxAuthService;
import com.stylefeng.guns.wx.modular.auth.util.CheckUtil;
import com.stylefeng.guns.wx.modular.auth.util.MessageUtil;
import com.stylefeng.guns.wx.modular.auth.util.WeixinUtil;
import com.stylefeng.guns.wx.modular.auth.util.mail.Mail;
import com.stylefeng.guns.wx.modular.auth.util.mail.MailUtil;
import org.dom4j.DocumentException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 请求验证的
 *
 * @author shaohaiting
 * @Date 2018/3/18 14:22
 */
@RestController
public class WxAuthController {
    @Resource
    MailUtil mailUtil;

    @Resource
    IWxAuthService wxAuthService;

    /**
     * key:openid
     * value: 验证码(邮箱)
     */
    static Map<String,String> codemap = new HashMap<>();
    @RequestMapping(value = "wxAuth")
    public void wxAuth(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if ("GET".equalsIgnoreCase(req.getMethod())) {
            doGet(req,resp);
        }else{
            doPost(req,resp);
        }
    }

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String signature = req.getParameter("signature");
        String timestamp = req.getParameter("timestamp");
        String nonce = req.getParameter("nonce");
        String echostr = req.getParameter("echostr");
        PrintWriter out = resp.getWriter();
        if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
            out.print(echostr);
        }
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        try {
            Map<String, String> map = MessageUtil.xmlToMap(req);
            String fromUserName = map.get("FromUserName");
            String toUserName = map.get("ToUserName");
            String msgType = map.get("MsgType");
            String content = map.get("Content");

            String message = null;
            if(MessageUtil.MESSAGE_TEXT.equals(msgType)){
                if(content.startsWith("邮箱:")){
                    String msg = content.replaceAll("邮箱:", "").trim();
                    try {
                        Mail mail = new Mail();
                        String code = (int)((Math.random()*9+1)*100000)+"";
                        codemap.put(fromUserName,code);
                        mail.setMsg("邮箱验证码:"+code);
                        mail.setSubject("公众号wx496767099");
                        mail.setToEmail(msg);
                        mailUtil.sendEmail(mail);
                        message = MessageUtil.initText(toUserName, fromUserName, wxAuthService.emailBind(fromUserName,msg));
                    }catch (Exception e){
                        System.out.println("绑定邮箱失败:"+e);
                        message = MessageUtil.initText(toUserName, fromUserName, "绑定失败!请检查邮箱是否正确?");
                        //不处理
                    }
                }else if(content.startsWith("验证邮箱:")){
                    String msg = content.replaceAll("验证邮箱:", "").trim();
                    String code = codemap.get(fromUserName);
                    if(null!=code && msg.equals(code)){
                        message = MessageUtil.initText(toUserName, fromUserName, wxAuthService.updateUseFlag(fromUserName));
                    }else{
                        message = MessageUtil.initText(toUserName, fromUserName, "验证码错误");
                    }
                }else if(content.startsWith("起点小说书号:")){
                    String msg = content.replaceAll("起点小说书号:", "").trim();
                    message = MessageUtil.initText(toUserName, fromUserName, wxAuthService.novelBind(fromUserName,msg));
                }
                else if(content.startsWith("取消关注书号:")){
                    String msg = content.replaceAll("取消关注书号:", "").trim();
                    message = MessageUtil.initText(toUserName, fromUserName, wxAuthService.delete(fromUserName,msg));
                }else if("关注列表".equals(content)){
                    message = MessageUtil.initText(toUserName, fromUserName, wxAuthService.novelList(fromUserName));
                }else if(content.startsWith("翻译")){
                    String word = content.replaceAll("^翻译", "").trim();
                    if("".equals(word)){
                        message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.threeMenu());
                    }else{
                        message = MessageUtil.initText(toUserName, fromUserName, WeixinUtil.translate(word));
                    }
                }else{
                    message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
                }
            }else if(MessageUtil.MESSAGE_EVNET.equals(msgType)){
                String eventType = map.get("Event");
                if(MessageUtil.MESSAGE_SUBSCRIBE.equals(eventType)){
                    message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
                }else if(MessageUtil.MESSAGE_CLICK.equals(eventType)){
                    message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
                }else if(MessageUtil.MESSAGE_VIEW.equals(eventType)){
                    String url = map.get("EventKey");
                    message = MessageUtil.initText(toUserName, fromUserName, url);
                }else if(MessageUtil.MESSAGE_SCANCODE.equals(eventType)){
                    String key = map.get("EventKey");
                    message = MessageUtil.initText(toUserName, fromUserName, key);
                }
            }else if(MessageUtil.MESSAGE_LOCATION.equals(msgType)){
                String label = map.get("Label");
                message = MessageUtil.initText(toUserName, fromUserName, label);
            }
            System.out.println(message);
            out.print(message);
        } catch (DocumentException e) {
            e.printStackTrace();
        }finally{
            out.close();
        }
    }
}
